﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GenericControlsWinForm
{
    public class NumberInt32TextBox : TextBox
    {
        public NumberInt32TextBox()
        {
            this.KeyPress += new KeyPressEventHandler(NumberInt32TextBox_KeyPress);
            updateLayout();
        }

        void NumberInt32TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (!CommomValidator.CharIsNumber(e.KeyChar))
                    e.Handled = true;
            }
            catch (Exception)
            {
                throw new Exception("Erro no componente NumberInt");
            }
        }

        void NumberIntTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (!CommomValidator.KeyIsNumber(e.KeyCode) && e.KeyCode != Keys.Tab && e.KeyCode != Keys.Subtract)
                    e.Handled = true;
                else if (e.KeyCode == Keys.Subtract)
                {
                    if (this.Text.Contains('-'))
                        e.Handled = true;
                    else
                    {
                        this.SelectionStart = 0;
                    }
                }
                else
                {
                    //Se for um número, valida o tamanho do número.
                    if (this.Text.Length == this.MaxLength - 1)
                    {
                        if (!this.Text.Contains('-'))
                            e.Handled = true;
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("Erro no componente NumberInt");
            }
        }

        internal virtual void updateLayout()
        {
            this.MaxLength = Int32.MaxValue.ToString().Length + 1;
            this.Width = 75;
        }
    }
}
